import sys
import sklearn
import numpy as np
import pandas as pd
D_FILE_PATH = "d_train.csv"
SYS_ENCODING = "ANSI"   # 实际运行时发现在Windows系统下打开csv文件需要指定编码

class Model():
    def __init__(self,**kwargs):
        from sklearn import datasets
        from sklearn.linear_model import LinearRegression
        self.model = LinearRegression()
    def train(self,X,y):
        self.model.fit(X,y)
        return self.model
    def predict(self,X):
        pred_y = self.model.predict(X)
        return pred_y
    def score(self,pred_y,y_test):
        f = 0
        for i in range(len(y_test)):
            f = f + (pred_y[i] - y_test[i]) * (pred_y[i] - y_test[i])
        # f = f / (2 * len(y_test))
        f = f / len(y_test)
        return f

if __name__ == '__main__':
    d_model = Model()
    # 从d_train.csv读取原始数据
    df = pd.read_csv(D_FILE_PATH, encoding=SYS_ENCODING)
    del df['体检日期']
    sex_map = {'男':1,'女':-1}
    df['性别'] = df['性别'].map(sex_map)

    # 用平均值填充缺失位置，并写进新的文件中
    before_mean = df.mean(axis = 0, skipna = True)
    fill_dict = {}
    for i in range(0,40):
        fill_dict[df.columns[i]] = before_mean[i]
    df.fillna(fill_dict,inplace = True)
    # df.to_csv('d_train_wash.csv',encoding = 'ANSI',index = 0)

    # 从清洗后的csv文件读取训练数据
    # df = pd.read_csv('d_train_wash.csv',encoding = SYS_ENCODING)
    df = df.iloc[:,1:]
    cols = list(df.columns.values)
    cols.remove('血糖')
    X_train = df[cols]
    Y_train = df['血糖']

    # 训练模型
    d_model.train(X_train, Y_train)

    # 从系统参数中获取测试文件，清洗之后进行预测
    df = pd.read_csv(sys.argv[1],encoding=SYS_ENCODING)
    del df['体检日期']
    sex_map = {'男':1,'女':-1}
    df['性别'] = df['性别'].map(sex_map)
    before_mean = df.mean(axis = 0, skipna = True)
    fill_dict = {}
    for i in range(0,40):
        fill_dict[df.columns[i]] = before_mean[i]
    df.fillna(fill_dict,inplace = True)
    df = df.iloc[:,1:]
    cols = list(df.columns.values)
    cols.remove('血糖')
    X_test = df[cols]
    Y_test = df['血糖']
    Y_predict = d_model.predict(X_test)
    point = d_model.score(Y_predict,Y_test)
    print("the score is : ",point)

